<template>
    <div class="goods-add-page">
        <div class="step-field">
            <el-steps :active="stepActive" finish-status="success" align-center simple>
                <el-step title="创建商品信息" description="商品基本信息" />
                <el-step title="上传商品图片" description="上传商品图片" />
                <el-step title="上传商品详情" description="上传商品详情" />
                <el-step title="商品上架"     description="上传商品详情" />
            </el-steps>
        </div>
        <div class="form-field">
            <!-- 商品基本信息 -->
            <div class="goods-info" v-if="stepActive == 0" v-loading="goodsBasicInfoLoading"
                element-loading-text="商品信息提交中。。。">
                <h1 class="title">步骤一：创建商品基本信息</h1>
                <el-form :model="addEditForm" :rules="addEditRules" ref="addEditRef" :label-width="120">
                    <el-form-item label="商品名称" prop="name">
                        <el-input v-model="addEditForm.name" autocomplete="off" placeholder="请输入商品名称" />
                    </el-form-item>
                    <el-form-item label="商品分类" prop="categoryId">
                        <el-select v-model="addEditForm.categoryId" placeholder="请选择商品分类" style="width: 100%">
                            <el-option v-for="option in goodsCategoryList" :key="option.id" :label="option.name"
                                :value="option.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="商品品牌" prop="brandName">
                        <el-input readonly v-model="addEditForm.brandName" autocomplete="off" placeholder="请输入商品品牌" />
                    </el-form-item>
                    <el-form-item label="商品编号" prop="sn">
                        <el-input v-model="addEditForm.sn" autocomplete="off" placeholder="请输入商品编号" />
                    </el-form-item>
                    <el-form-item label="商品成本价" prop="cost">
                        <el-input v-model="addEditForm.cost" autocomplete="off" placeholder="请输入商品成本价" />
                    </el-form-item>
                    <el-form-item label="商品市场价" prop="marketPrice">
                        <el-input v-model="addEditForm.marketPrice" autocomplete="off" placeholder="请输入商品市场价" />
                    </el-form-item>
                    <el-form-item label="商品售价" prop="actualPrice">
                        <el-input v-model="addEditForm.actualPrice" autocomplete="off" placeholder="请输入商品售价" />
                    </el-form-item>
                    <el-form-item label="商品参数" prop="params">
                        <div class="param-item" v-for="(paramItem, paramIndex) in addEditForm.paramList" :key="paramItem"
                            style="width: 100%;margin-bottom: 10px;">
                            <div class="param-item-key">
                                <el-input style="flex:1;" placeholder="输入参数名" v-model="paramItem.key"></el-input>
                            </div>
                            <el-button @click="removeParam(paramIndex)" style="margin-left:5px"
                                type="danger">删除参数项</el-button>
                            <span style="padding: 0 5px">:</span>
                            <div class="param-item-value">
                                <el-input style="flex:1" placeholder="输入参数值" v-model="paramItem.value"></el-input>
                            </div>
                        </div>
                        <a class="add-params-btn" @click="addGoodsParams">新增商品参数</a>
                    </el-form-item>
                    <el-form-item label="商品规格" prop="specs">
                        <div class="specs-item" v-for="(specItem, specIndex) in addEditForm.specList"
                            :key="specItem.toString()" style="width: 100%;margin-bottom: 10px;">
                            <div class="specs-item-key">
                                <el-input style="flex:1;" placeholder="输入规格名" v-model="specItem.key"></el-input>
                            </div>
                            <el-button @click="removeSpec(specIndex)" style="margin-left:5px"
                                type="danger">删除规格项</el-button>
                            <span style="padding: 0 5px">:</span>
                            <div class="specs-item-value">
                                <div class="specs-value-item" v-for="(valueItem, valueIndex) in specItem.valueList"
                                    :key="valueItem.toString()">
                                    <el-input style="flex:1" placeholder="输入规格值" v-model="valueItem.value"></el-input>
                                    <el-button @click="removeSpecValue(specIndex, valueIndex)" style="margin-left:5px"
                                        type="danger">删除规格值</el-button>
                                </div>
                                <el-button @click="addSpecItem(specIndex)" style="margin-left:5px"
                                    type="primary">新增规格值</el-button>
                            </div>
                        </div>
                        <a class="add-specs-btn" @click="addGoodsSpecs">新增商品规格</a>
                    </el-form-item>

                    <el-form-item label="是否允许团购" prop="allowGroupBuy">
                        <el-select v-model="addEditForm.allowGroupBuy" placeholder="请选择是否支持团购" style="width: 100%">
                            <el-option v-for="option in allowGroupBuyList" :key="option.id" :label="option.name"
                                :value="option.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="团购优惠" prop="allowGroupBuy">
                        <el-select v-model="addEditForm.groupBuyDiscountType" placeholder="请选择是否支持团购" style="width: 100%">
                            <el-option v-for="option in groupBuyDiscountTypeList" :key="option.id" :label="option.name"
                                :value="option.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item v-if="addEditForm.groupBuyDiscountType===1"  label="团购优惠金额" prop="groupBuyDiscount">
                        <el-input style="width:100%"  v-model="addEditForm.groupBuyDiscount"
                            autocomplete="off" placeholder="请输入团购优惠金额" />
                    </el-form-item>
                    <el-form-item  v-if="addEditForm.groupBuyDiscountType===2" label="团购优惠折扣" prop="groupBuyDiscount">
                        <el-input-number style="width:300px" :min="1" :max="100" v-model="addEditForm.groupBuyDiscount"
                            autocomplete="off" placeholder="请输入团购优惠折扣(1~100)" />
                    </el-form-item>
                    <el-form-item label="库存量" prop="store">
                        <el-input-number style="width:200px" :min="1" :max="9999" v-model="addEditForm.store"
                            autocomplete="off" placeholder="请输入库存量" />
                    </el-form-item>
                    <el-form-item label="排序" prop="sort">
                        <el-input-number style="width:200px" :min="0" :max="99" v-model="addEditForm.sort"
                            autocomplete="off" placeholder="请输入排序值" />
                    </el-form-item>
                    <div class="btn-field">
                        <el-button class="goods-basic-info-btn" @click="requestGoodsInfo">创建商品基本信息</el-button>
                    </div>
                </el-form>
            </div>

            <!-- 商品的产品图 -->
            <div class="goods-product-img" v-if="stepActive==1" v-loading="goodsProductImgLoading" 
                    element-loading-text="商品图信息提交中。。。">
                <h1 class="title">步骤二：上传商品图</h1>
                <el-form :model="addEditForm" :rules="addEditRules" ref="addEditRef" :label-width="120">
                    <el-form-item label="商品展示图" prop="coverUrl">
                        <div>
                            <el-upload :limit="1" v-if="!goodsProductImgForm.coverUrl" style="width: 220px;height:233px"
                                ref="upload" class="upload-demo" drag :before-upload="canUpload" :http-request="(option: any): any => {
                                    handleUpload(option, 1, -1, -1);
                                }" :on-success="uploadSuccess" :on-error="uploadError" :show-file-list="false">
                                <el-icon class="el-icon--upload">
                                    <UploadFilled />
                                </el-icon>
                                <div class="el-upload__text">将 "商品列表展示图" 拖到此处, 或<em>点击上传</em></div>
                            </el-upload>
                            <div v-else style="position: relative;border:1px dashed #ddd;border-radius: 8px;">
                                <el-image preview-teleported="true" :preview-src-list="goodsProductImgForm.coverPreviewList" fit="cover"
                                    style="width: 220px;height:220px" :src="goodsProductImgForm.coverUrl"></el-image>
                                <el-button @click="removeCoverUrl"
                                    style="background-color: transparent;position: absolute;border:none;top:-12px;right:-24px;">
                                    <el-icon
                                        style="color:#f00;height: 24px;width: 24px;border-radius: 12px; border:1px solid #f00;padding: 4px">
                                        <CloseBold />
                                    </el-icon>
                                </el-button>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item prop="name" v-for="(item, index) in goodsProductImgForm.productImgList"
                        :key="item.toString()" :label="`商品轮播图` + (index + 1)">
                        <div>
                            <div style="margin-bottom: 10px;">
                                <div class="select-item" style="margin-bottom: 8px;width:310px">
                                    <el-select v-model="item.sourceType" placeholder="请选择是上传图片还是视频" style="width: 100%">
                                        <el-option v-for="option in fileTypeList" :key="option.id" :label="option.name"
                                            :value="option.id" />
                                    </el-select>
                                    <el-button type="danger" @click="removeProductImg(index)">删除</el-button>
                                </div>
                                <div class="good-product-img-item">
                                    <el-upload v-show="item.sourceType" v-if="!item.url" 
                                        auto-upload class="upload-demo" ref="upload" drag :before-upload="( rawFile )=>{
                                           return canUpload( rawFile, item.sourceType )
                                        }"
                                        :http-request="(option: any): any => {
                                            handleUpload(option, 2, index, item.sourceType);
                                        }" :on-success="uploadSuccess" :on-error="uploadError" :show-file-list="false">
                                        <el-icon class="el-icon--upload">
                                            <UploadFilled />
                                        </el-icon>
                                        <div class="el-upload__text">将 "商品轮播图{{ item.sourceType==2?"视频":"图片" }}" 拖到此处, 或<em>点击上传</em></div>
                                    </el-upload>
                                    <div v-else style="position: relative;border:1px dashed #ddd;border-radius: 12px;">
                                        <div @click="toVideoPreview(index, 1)" v-if="item.sourceType==2">
                                            <el-image   fit="cover"
                                                style="width: 300px;height:300px"
                                                :src="item.url"></el-image>
                                                <el-icon  style="cursor: pointer;;font-size: 64px; margin-left: -24px; margin-top: -24px;left: 50%; top: 50%;color: #fff;position: absolute ;"><VideoPlay /></el-icon>
                                        </div>
                                        <el-image v-else :preview-src-list="item.previewList" fit="cover" preview-teleported="true"
                                            style="width: 300px;height:300px"
                                            :src="item.url"></el-image>
                                        <el-button @click="removeProductUrl(index)"
                                            style="background-color: transparent;position: absolute;border:none;top:-12px;right:-24px;">
                                            <el-icon
                                                style="color:#f00;height: 24px;width: 24px;border-radius: 12px; border:1px solid #f00;padding: 4px">
                                                <CloseBold />
                                            </el-icon>
                                        </el-button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item :label="goodsProductImgForm.productImgList.length > 0 ? '' : `商品详情轮播图`">
                        <el-button type="primary" @click="addProductImg">新增商品轮播图</el-button>
                    </el-form-item>
                </el-form>
                <div class="btn-field">
                    <el-button class="goods-product-img-btn" @click="requestGoodsProductImg">确定上传商品图片</el-button>
                </div>
            </div>

            <!-- 商品的详情图 -->
            <div class="goods-detail-img" v-if="stepActive ==2" v-loading="goodsDetailImgLoading"
                element-loading-text="商品详情图信息提交中。。。">
                <h1 class="title">步骤三：上传商品详情图</h1>
                <el-form :model="addEditForm" :rules="addEditRules" ref="addEditRef" :label-width="120">
                    <el-form-item prop="name" v-for="(item, index) in goodsDetailImgForm.detailImgList"
                        :key="item.toString()" :label="`商品详情图` + (index + 1)">
                        <div>
                            <div style="margin-bottom: 10px;">
                                <div class="select-item" style="margin-bottom: 8px;width:310px">
                                    <el-select v-model="item.sourceType" placeholder="请选择是上传图片还是视频" style="width: 100%">
                                        <el-option v-for="option in fileTypeList" :key="option.id" :label="option.name"
                                            :value="option.id" />
                                    </el-select>
                                    <el-button type="danger" @click="removeDetailImg(index)">删除</el-button>
                                </div>
                                <div class="good-detail-img-item">
                                    <el-upload v-show="item.sourceType" v-if="!item.url" 
                                        auto-upload class="upload-demo" ref="upload" drag :before-upload="( rawFile )=>{
                                           return canUpload( rawFile, item.sourceType )
                                        }"
                                        :http-request="(option: any): any => {
                                            handleUpload(option, 3, index, item.sourceType);
                                        }" :on-success="uploadSuccess" :on-error="uploadError" :show-file-list="false">
                                        <el-icon class="el-icon--upload">
                                            <UploadFilled />
                                        </el-icon>
                                        <div class="el-upload__text">将 "商品详情图{{ item.sourceType==2?"视频":"图片" }}" 拖到此处, 或<em>点击上传</em></div>
                                    </el-upload>
                                    <div v-else style="position: relative;border:1px dashed #ddd;border-radius: 12px;">
                                        <div @click="toVideoPreview(index, 2)" v-if="item.sourceType==2">
                                            <el-image   fit="cover"
                                                style="width: 300px;height:300px"
                                                :src="item.url"></el-image>
                                                <el-icon  style="cursor: pointer;;font-size: 64px; margin-left: -24px; margin-top: -24px;left: 50%; top: 50%;color: #fff;position: absolute ;"><VideoPlay /></el-icon>
                                        </div>
                                        <el-image v-else :preview-src-list="item.previewList" fit="cover" preview-teleported="true"
                                            style="width: 300px;height:300px"
                                            :src="item.url"></el-image>
                                        <el-button @click="removeDetailUrl(index)"
                                            style="background-color: transparent;position: absolute;border:none;top:-12px;right:-24px;">
                                            <el-icon
                                                style="color:#f00;height: 24px;width: 24px;border-radius: 12px; border:1px solid #f00;padding: 4px">
                                                <CloseBold />
                                            </el-icon>
                                        </el-button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-form-item>
                    <el-form-item :label="goodsDetailImgForm.detailImgList.length > 0 ? '' : `商品详情图`">
                        <el-button type="primary" @click="addDetailImg">新增商品详情图</el-button>
                    </el-form-item>
                </el-form>
                <div class="btn-field">
                    <el-button class="goods-detail-img-btn" @click="requestGoodsDetailImg">上传商品详情图</el-button>
                </div>
            </div>

            <div class="goods-grounding" v-if="stepActive == 3" v-loading="goodsGroundingLoading"
                element-loading-text="商品上架信息提交中。。。">
                <h1 class="title">步骤四：上架商品</h1>
                <el-form :model="addEditForm" :rules="addEditRules" ref="addEditRef" :label-width="120">
                    <el-form-item label="是否定时上架" prop="name">
                        <el-select v-model="groundingForm.delayGroudingType" placeholder="请选择是否定时上架" style="width: 100%">
                            <el-option v-for="option in delayGroundingTypeList" :key="option.id" :label="option.name"
                                :value="option.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item  v-if="groundingForm.delayGroudingType==2" label="定时上架时间" prop="name">
                        <el-date-picker
                            style="width: 300px"
                            v-model="groundingForm.delayTime"
                            type="datetime"
                            placeholder="选择定时上架的日期"
                            format="YYYY/MM/DD HH:mm:ss"
                            :disabled-date="(time) => {
                                //如果是同一天，那么就设置可以选取的时分秒
                                return time.getTime() <= Date.now() - 3600 * 24 * 1000;
                            }"
                        />
                    </el-form-item>
                    <div class="btn-field">
                        <el-button class="goods-grounding-btn" @click="requestGoodsGrounding">上架商品</el-button>
                    </div>
                </el-form>
            </div>
        </div>


        <view v-if="showVideoPreview" style="position: fixed;display: flex;justify-content: center;align-items: center;left:224px;right:0;bottom:0;top:60px;background-color: #0007;">
            <el-button @click="hiddenVideoPreview" style="background-color: transparent;position: absolute;border:none;top:50px;right:50px;">
                    <el-icon
                    style="font-size: 24px;color:#fff;height: 48px;width: 48px;border-radius: 24px; border:1px solid #fff;padding: 4px">
                    <CloseBold />
                </el-icon>
            </el-button>
            <video autoplay  style="width: 300px" ref="videoPlayer" controls v-if="previewVideoUrl">
                <source :src="previewVideoUrl" type="video/mp4" />
            </video>
        </view>
    </div>
</template>
<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import TimeUtils from '@/utils/TimeUtils'
import { getOssPolicy } from '@/api/oss-upload.api'
import {
    getGoodsCategoryAllList,
    addGoodsInfo,
    updateGoodsProductImgOrVideo,
    updateGoodsDetailImg,
    groundingGoodsInfo
} from '@/api/goods-manage.api'
import axios from 'axios'
import { ElMessage, ElUpload, ElIcon, } from "element-plus";
import { UploadFilled, CloseBold,VideoPlay } from "@element-plus/icons-vue";
const $router =  useRouter();
const stepActive = ref(0);
const goodsBasicInfoLoading = ref(false);
const goodsProductImgLoading = ref(false);
const goodsDetailImgLoading = ref(false);
const goodsGroundingLoading = ref(false);
const fileTypeList = [
    {
        id: 1,
        name: "图片"
    },
    {
        id: 2,
        name: "视频"
    }
]

const showVideoPreview = ref(false)
const addEditForm = reactive({
    id: '1737128900944539649',
    name: '测试商品',
    categoryId: '1737031835522478082',
    brandName: '袋鼠医生',
    sn: '1737031835522478082',
    cost: 25.4,
    marketPrice: 30.82,
    actualPrice: 26,
    allowGroupBuy: 0,
    groupBuyDiscountType: 0,
    groupBuyDiscount: '',
    paramList: [{
        key: "香型",
        value: "酱香型"
    }, {
        key: "包装形式",
        value: "礼盒装"
    }, {
        key: "单件容量",
        value: "50ml"
    }
    ],

    specList: [{
        key: "选择颜色",
        valueList: [{
            value: "红色"
        },
        {
            value: "蓝色"
        },
        {
            value: "白色"
        },
        {
            value: "紫色"
        }
        ]
    },
    {
        key: "尺寸",
        valueList: [
            {
                value: "大"
            },
            {
                value: "中"
            },
            {
                value: "小"
            }
        ]
    }
    ],
    store: 999,
    sort: 0
});

const groundingForm = reactive({
    delayGroudingType: 1,
    delayTime: ''
})
const delayGroundingTypeList = [
    {
        id: 1,
        name: "立即上架"
    },
    {
        id: 2,
        name: "延迟上架"
    }
]
const allowGroupBuyList = [
    {
        id: 0,
        name: "允许"
    },
    {
        id: 1,
        name: "不允许"
    }
]
const groupBuyDiscountTypeList=[
    {
        id: 0,
        name: "无优惠"
    },
    {
        id: 1,
        name: "金额直减"
    },
    {
        id: 2,
        name: "百分比折扣"
    }
]


/**************************************************/
const goodsDetailImgForm = reactive({
    detailImgList: [
        {
            sourceType: '',
            type: 1,
            url: '',
            videoUrl: '',
            previewList: []
        }
    ]
})

const addDetailImg = ()=>{
    goodsDetailImgForm.detailImgList.push({
        sourceType: '',
        url: '',
        type: 1,
        videoUrl: '',
        previewList: []
    })
}

const removeDetailImg = (index:number)=>{
    goodsDetailImgForm.detailImgList = goodsDetailImgForm.detailImgList.filter((_, rowIndex) => {
        return index != rowIndex;
    });
}

const removeDetailUrl = ( index:number )=>{
    let detailImgItem = goodsDetailImgForm.detailImgList[index];
    detailImgItem.url = "";
    detailImgItem.videoUrl = "";
    detailImgItem.previewList = [];
}

/**************************************************/
const goodsProductImgForm = reactive({
    coverUrl: '',
    coverPreviewList: [],
    productImgList: []
})
const removeCoverUrl = () => {
    goodsProductImgForm.coverUrl = "";
    goodsProductImgForm.coverPreviewList = [];
}


const addProductImg = () => {
    goodsProductImgForm.productImgList.push({
        sourceType: '',
        type: 0,
        url: '',
        videoUrl: '',
        previewList: []
    })
}
const removeProductImg = (index: number) => {
    goodsProductImgForm.productImgList = goodsProductImgForm.productImgList.filter((_, rowIndex) => {
        return index != rowIndex;
    });
}
const removeProductUrl = (index:number)=>{
    let productImgItem = goodsProductImgForm.productImgList[index];
    productImgItem.url = "";
    productImgItem.videoUrl = "";
    productImgItem.previewList = [];
}

const canUpload = async (rawFile, sourceType:number) => {

    let name = rawFile.name;
    let index = name.indexOf(".");
    let exet = name.substring(index + 1);

    if( sourceType == 2  ){
        if( exet !== 'mp4'){
            ElMessage({
                message: "只能接受 mp4 格式的视频文件",
                type: "error",
            });
           return Promise.reject();
        }
        return true;
    }

    if (!(exet === "jpg" || exet === 'png' || exet === "jpeg" || exet == 'webp')) {
        ElMessage({
            message: "只能接受 jpg/png/webp 格式的图片文件",
            type: "error",
        });
        return Promise.reject();
    }
    return true;
};

const handleUpload = async (option, type: number, index: number, productType: number) => {

    //生成随机的图片文件名称。
    console.log("option: ", option)
    let fileName = option.file.name;

    let res: {
        host: string,
        accessid: string,
        policy: string,
        signature: string,
        dir: string
        expire: string
    } = <any>await getOssPolicy();
    let url = res.host;
    let formData = new FormData();
    formData.append("OSSAccessKeyId", res.accessid);
    formData.append("policy", res.policy);
    formData.append("Signature", res.signature);
    formData.append("key", `${res.dir}${fileName}`);
    formData.append("expire", res.expire);
    formData.append("success_action_status", '200');
    formData.append("file", option.file);
    try {
        let fileRes = await axios.post(url, formData);
        if (type == 1 ) {
            let fileUrl = `${url}/${res.dir}${fileName}`;
            goodsProductImgForm.coverUrl = fileUrl;
            goodsProductImgForm.coverPreviewList = [goodsProductImgForm.coverUrl];
        } else if( type==2 && productType == 1 ){
            let fileUrl = `${url}/${res.dir}${fileName}`;
            let productImgItem = goodsProductImgForm.productImgList[index];
            productImgItem.url = fileUrl;
            productImgItem.videoUrl = fileUrl;
            productImgItem.previewList = [fileUrl];
        } 
        else if (type == 2 && productType == 2 ) {
            let fileUrl = `${url}/${res.dir}${fileName}`;
            let productImgItem = goodsProductImgForm.productImgList[index];
            productImgItem.url = fileUrl+"?x-oss-process=video/snapshot,t_1000,m_fast";
            productImgItem.previewList = [fileUrl];
            productImgItem.videoUrl = fileUrl;
        }
        else if( type == 3  && productType == 1  ){
            let fileUrl = `${url}/${res.dir}${fileName}`;
            let detailImgItem = goodsDetailImgForm.detailImgList[index];
            detailImgItem.url = fileUrl;
            detailImgItem.videoUrl = fileUrl;
            detailImgItem.previewList = [fileUrl];

        } else if (type == 3 && productType == 2 ) {

            let fileUrl = `${url}/${res.dir}${fileName}`;
            let detailImgItem = goodsDetailImgForm.detailImgList[index];
            detailImgItem.url = fileUrl+"?x-oss-process=video/snapshot,t_1000,m_fast";
            detailImgItem.previewList = [fileUrl];
            detailImgItem.videoUrl = fileUrl;
        }
        console.log("url地址: ", `${url}/${res.dir}${fileName}`)
        console.log("fileRes: ", fileRes);
    } catch (err) {
        console.log("...", err)
    }
}

const uploadError = (err) => {
    ElMessage({
        message: err.msg || err,
        type: "error",
    });
};

const uploadSuccess = () => {
    console.log("图片上传成功...")
}

const previewVideoUrl = ref("")
const toVideoPreview = (index:number, sourceType:number)=>{

    if( sourceType == 1 ){
        let productImgItem = goodsProductImgForm.productImgList[index];
        previewVideoUrl.value = productImgItem.videoUrl
        showVideoPreview.value = true;
    }else if( sourceType == 2 ){
        let detailImgItem = goodsDetailImgForm.detailImgList[index];
        previewVideoUrl.value = detailImgItem.videoUrl
        showVideoPreview.value = true;
    }

}
const hiddenVideoPreview = ()=>{
    previewVideoUrl.value = "";
    showVideoPreview.value = false;
}

const addEditRules = {

}


const addGoodsParams = () => {
    addEditForm.paramList.push({
        key: '',
        value: ''
    })
}

const removeParam = (parmaIndex: number) => {
    addEditForm.paramList = addEditForm.paramList.filter((_, index) => {
        return parmaIndex != index;
    })
}

const addGoodsSpecs = () => {
    addEditForm.specList.push({
        key: "",
        valueList: [{
            value: ""
        }]
    })
}

const removeSpec = (specIndex: number) => {
    addEditForm.specList = addEditForm.specList.filter((_, index) => {
        return specIndex != index;
    })
}

const removeSpecValue = (specIndex: number, valueIndex: number) => {
    let specItem = addEditForm.specList[specIndex];
    specItem.valueList = specItem.valueList.filter((_, subIndex) => {
        return valueIndex != subIndex;
    });
}

const addSpecItem = (specIndex: number) => {
    let specItem = addEditForm.specList[specIndex];
    specItem.valueList.push({
        value: ""
    })
    console.log(specIndex, specItem.valueList.length)
}


/***
 * 增加商品基本信息
 */
const requestGoodsInfo = () => {

    goodsBasicInfoLoading.value = true;
    let formData = {
        name: addEditForm.name,
        categoryId: addEditForm.categoryId,
        brandName: addEditForm.brandName,
        sn: addEditForm.sn,
        cost: addEditForm.cost*100,
        marketPrice: addEditForm.marketPrice*100,
        actualPrice: addEditForm.actualPrice*100,
        paramList: addEditForm.paramList,
        specList: addEditForm.specList,
        allowGroupBuy: addEditForm.allowGroupBuy, //是否允许团购
        groupBuyDiscountType: addEditForm.groupBuyDiscountType, //优惠类型
        groupBuyDiscount: addEditForm.groupBuyDiscount, //优惠金额或者比例
        store: addEditForm.store,
        sort: addEditForm.sort,
    }
    addGoodsInfo(formData).then((res: any) => {
        ElMessage({
            type: "success",
            message: "创建商品信息成功"
        })
        addEditForm.id = res;
        goodsBasicInfoLoading.value = false;
        stepActive.value = stepActive.value+1;
    }).catch(err => {
        goodsBasicInfoLoading.value = false;
        ElMessage({
            type: "error",
            message: err.msg || err || "操作失败，请稍后再试"
        })
    });
}

/***
 * 增加商品产品图片和视频
 */
const requestGoodsProductImg = ()=>{

    goodsProductImgLoading.value = true;
    let formData = {
        goodsId: addEditForm.id,
        coverUrl: goodsProductImgForm.coverUrl,
        productImgList: []
    }
    let productImgList = goodsProductImgForm.productImgList || [];
    if( productImgList.length > 0 ){
        formData.productImgList = productImgList.map( item=>{
            return {
                sourceType: item.sourceType,
                type: 0,
                url: item.videoUrl
            }
        });
    }   

    updateGoodsProductImgOrVideo( formData ).then( ()=>{
        ElMessage({
            type: "success",
            message: "商品图片上传成功"
        })
        goodsProductImgLoading.value = false;
        stepActive.value = stepActive.value+1;
    }).catch( err=>{
        goodsProductImgLoading.value = false;
        ElMessage({
            type: "error",
            message: err.msg || err || "操作失败，请稍后再试"
        })
    } );
}


/***
 * 增加商品详情图片
 * */
const requestGoodsDetailImg = ()=>{
    let formData = {
        goodsId: addEditForm.id,
        detailImgList: goodsDetailImgForm.detailImgList,
    }
    updateGoodsDetailImg(formData).then( res=>{
        console.log(res)
        stepActive.value = stepActive.value+1;
        ElMessage({
            type: "success",
            message: "更新商品图片"
        })
    }).then( err=>{
        goodsProductImgLoading.value = false;
        ElMessage({
            type: "error",
            message: err.msg || err || "操作失败，请稍后再试"
        })
    } );
}

/***
 * 商品上架
 */
const requestGoodsGrounding = ()=>{
    let formData = {
        goodsId: addEditForm.id,
        grounding: 1,
    }

    let nowString = TimeUtils.format(new Date());
    if( groundingForm.delayGroudingType == 2 ){
        if( nowString > groundingForm.delayTime ){
            ElMessage({
                type: 'error',
                message: "定时上架不能选择低于当前的时间"
            })
            return;
        }
    }

    //立即发布，则设置当前时间
    if( groundingForm.delayGroudingType == 1 ){
        formData.delayTime = TimeUtils.format(new Date());
    } 

    groundingGoodsInfo(formData).then( ()=>{
        goodsGroundingLoading.value = false;
        ElMessage({
            type: "success",
            message: "商品上架成功"
        })
        setTimeout(() => {
            $router.replace("/goods/good")
        }, 1000);

    } ).catch( err=>{
        goodsGroundingLoading.value = false;
        ElMessage({
            type: "error",
            message: err.msg || err || "操作失败，请稍后再试"
        })
    } )
}


/***
 * 商品上架
 */

onMounted(() => {
    requestGoodsCategoryAllList();
})

const goodsCategoryList = ref([])
const requestGoodsCategoryAllList = () => {
    getGoodsCategoryAllList({}).then((res: any) => {
        goodsCategoryList.value = res;
        console.log("getGoodsCategoryAllList: ", res)
    }).catch(err => {
        console.log(err)
    })
}

</script>
<style lang="scss" scoped>
@import "./GoodsAdd.scss";
</style>
